const fs = require('fs-extra')
const inquirer = require('inquirer')
const { rcPath, isExistRcPath } = require('./util')

const { presets = [] } = isExistRcPath ? fs.readJSONSync(rcPath) : {}
const presetNameList = presets.map(item => item.name)

const handlePresets = async mapCollections => {
	const { isPreset } = await inquirer.prompt([
		{
			type: 'confrim',
			name: 'isPreset',
			message: '将此保存为将来项目的预设？(Y/N)'
		},
	])
	if (isPreset.toLowerCase() === 'y') {
		
		const { presetName } = await inquirer.prompt([
			{
				type: 'input',
				name: 'presetName',
				message: '将预设另存为',
				validate (input) {
					if (!input) {
						return '名字不能为空！'
					}
					if (input.toLowerCase() === 'manually') {
						return `"${input}"为保留名称,请输入其它名称！`
					}
					if (presetNameList.includes(input)) {
						return '名字已存在！'
					}
					return true
				}
			}
		])
		presets.push({ ...mapCollections, name: presetName })
		fs.writeJSONSync(rcPath, { presets })
	}
}

module.exports = {
	handlePresets,
	presets,
	presetNameList 
}